﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PosClient.Model;
using PosClient.Helper;

namespace PosClient.Service
{
    public class OrderService
    {
        public static string GetCurrentOrderNo()
        {
            using (var conn = FreeClient.Sqlite)
            {
                OrderSeq seq = conn.Select<OrderSeq>().ToList().FirstOrDefault();
                bool exists = true;
                if (seq == null)
                {
                    seq = new OrderSeq { Id = 1 };
                    exists = false;
                }
                else
                {
                    seq.Id++;
                }
                seq.Id = seq.Id % 10000;
                string id = seq.Id.ToString();
                if (exists)
                {
                    conn.Update<OrderSeq>()
                        .Set(it => it.Id, seq.Id)
                        .Where(x => x.Id == 1)
                        .ExecuteAffrows();
                }
                else
                {
                    conn.Insert(new OrderSeq() { Id = seq.Id }).ExecuteAffrows();
                }
                return DateTime.Now.ToString("yyyyMMdd") + Globals.Pos + GetCurrentSeconds().PadLeft(2, '0') + id.PadLeft(5, '0');
            }
        }

        private static string GetCurrentSeconds()
        {
            return (DateTime.Now.Second % 86400).ToString();
        }
    }
}
